package xcmg.device.web.company;

import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import xcmg.device.dao.entity.company.SupplierDealerSearchParam;
import xcmg.device.infra.AuthCode;
import xcmg.device.infra.BasicController;
import xcmg.device.infra.ErrorCode;
import xcmg.device.infra.exception.CommonBusiExceptions;
import xcmg.device.service.company.ClientReceiverInfoService;
import xcmg.device.service.company.CompanyDealerLatLngService;
import xcmg.device.service.company.CompanyDealerService;
import xcmg.device.service.param.CompanyDealerParam;
import xcmg.device.service.vo.FunctionResult;
import xcmg.device.service.vo.company.ClientReceiverInfoVO;
import xcmg.device.service.vo.company.CompanyDealerVO;
import xcmg.device.service.vo.company.InvitationCodeVO;
import xcmg.device.service.vo.warehouse.WarehouseDealerAuthVO;
import xcmg.device.service.warehouse.WarehouseCompose;
import xcmg.device.util.CompanyUtil;
import xcmg.device.util.GeoUtil;
import yb.ecp.fast.infra.annotation.FastMappingInfo;
import yb.ecp.fast.infra.infra.ActionResult;
import yb.ecp.fast.infra.infra.PageCommonVO;
import yb.ecp.fast.infra.infra.SearchCommonVO;
import yb.ecp.fast.infra.util.StringUtil;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * Created by sqq on 2017/12/22.
 */
@RestController
@RequestMapping("/companyDealer")
public class CompanyDealerController extends BasicController {

    @Autowired
    private CompanyDealerService companyDealerService;

    @Autowired
    private WarehouseCompose warehouseCompose;

    @Autowired
    private CompanyDealerLatLngService companyDealerLatLngService;

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private CompanyUtil companyUtil;

    @Autowired
    private ClientReceiverInfoService clientReceiverInfoService;

    @RequestMapping(value = "/insert", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true, code = AuthCode.Client.ADD)
    public ActionResult<String> insert(@RequestBody CompanyDealerVO companyDealerVO) throws Exception {
        companyDealerVO.setUpdateId(getUserId(request));
        companyDealerVO.setCreateId(getUserId(request));
        companyDealerVO.setCreateName(getUserName());
        companyDealerVO.setOrgId(getOrgId());
        ErrorCode code = companyDealerService.insert(companyDealerVO);
        return actionResult(code);
    }


    /**
     * 根据orgId查询服务站信息
     *
     * @param platOrgId
     * @return
     */
    @RequestMapping(value = "/queryByOrgId", method = RequestMethod.GET)
    public ActionResult<CompanyDealerVO> queryByOrgId(@RequestParam("platOrgId") String platOrgId) {
        CompanyDealerVO param = new CompanyDealerVO();
        param.setPlatOrgId(platOrgId);
        param.setDealerTypeList(Arrays.asList(5, 50));
        CompanyDealerVO r = companyDealerService.queryByParam(param);
        return actionValueResult(r);
    }

    @RequestMapping(value = "/queryYnOrgId", method = RequestMethod.GET)
    public ActionResult<String> queryYnOrgId() {
        return actionValueResult(companyUtil.ynOrgId());
    }


//    @RequestMapping(value = "/getSap", method = RequestMethod.GET)
//    @FastMappingInfo(needLogin = true, code = AuthCode.Client.CLIENT_UPDATE)
//    public void getSap() throws Exception {
//        companyDealerService.getSap(getOrgId());
//
//    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true, code = AuthCode.Client.EDIT)
    public ActionResult<String> update(@RequestBody CompanyDealerVO companyDealerVO) {
        if (companyDealerVO.getId() == null || companyDealerVO.getId() <= 0) {
            return actionResult(ErrorCode.IllegalArument);
        }
        companyDealerVO.setUpdateId(getUserId(request));
        ErrorCode code = companyDealerService.update(companyDealerVO);
        return actionResult(code);
    }

    @RequestMapping(value = "/remove", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true, code = AuthCode.Client.DEL)
    public ActionResult<String> delete(@RequestBody CompanyDealerVO companyDealerVO) {
        if (companyDealerVO.getIds() == null) {
            return actionResult(ErrorCode.IllegalArument);
        }
        companyDealerVO.setUpdateId(getUserId(request));
        ErrorCode code = companyDealerService.delete(companyDealerVO.getIds(), getUserId());
        return actionResult(code);
    }


    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult<Object> list(@RequestBody SearchCommonVO<CompanyDealerVO> condition) throws Exception {
        CompanyDealerVO companyDealerVO = condition.getFilters();
        if (companyDealerVO == null) {
            companyDealerVO = new CompanyDealerVO();
        }
        if (companyDealerVO.getOrgId() == null) {
            companyDealerVO.setOrgId(getOrgId());
        }
        condition.setFilters(companyDealerVO);
        PageCommonVO<CompanyDealerVO> pageCommonVO = companyDealerService.list(condition);
        return actionValueResult(pageCommonVO.getPageInfo());
    }

    @RequestMapping(value = "/listForPriceScheme", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult<PageInfo<CompanyDealerVO>> listForPriceScheme(@RequestBody SearchCommonVO<CompanyDealerVO> condition) throws Exception {
        CompanyDealerVO companyDealerVO = condition.getFilters();
        if (companyDealerVO == null) {
            companyDealerVO = new CompanyDealerVO();
        }
        if (companyDealerVO.getOrgId() == null) {
            companyDealerVO.setOrgId(getOrgId());
        }
        condition.setFilters(companyDealerVO);
        PageCommonVO<CompanyDealerVO> pageCommonVO = companyDealerService.listForPriceScheme(condition);
        return actionValueResult(pageCommonVO.getPageInfo());
    }

    @RequestMapping(value = "/listByCurrentId", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult<PageInfo<CompanyDealerVO>> listByCurrentId(@RequestBody SearchCommonVO<CompanyDealerVO> condition) throws Exception {
        CompanyDealerVO companyDealerVO = condition.getFilters();
        if (companyDealerVO == null) {
            companyDealerVO = new CompanyDealerVO();
        }
        if (companyDealerVO.getOrgId() == null) {
            companyDealerVO.setOrgId(getOrgId());
        }
        companyDealerVO.setCurrentId(getUserId());
        condition.setFilters(companyDealerVO);
        PageCommonVO<CompanyDealerVO> pageCommonVO = companyDealerService.listByCurrentId(condition);
        return actionValueResult(pageCommonVO.getPageInfo());
    }

    @RequestMapping(value = "/listBySupplierId", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    @ApiOperation(value = "根据供应商ID查询客户信息（不包括自己）")
    public ActionResult<PageInfo<WarehouseDealerAuthVO>> listBySupplierId(@RequestBody SearchCommonVO<CompanyDealerVO> condition) throws Exception {
        CompanyDealerVO companyDealerVO = condition.getFilters();
        if (companyDealerVO == null) {
            companyDealerVO = new CompanyDealerVO();
        }
        if (companyDealerVO.getOrgId() == null) {
            companyDealerVO.setOrgId(getOrgId());
        }
        companyDealerVO.setCurrentId(getOrgId());
        condition.setFilters(companyDealerVO);
        PageCommonVO<WarehouseDealerAuthVO> pageCommonVO = companyDealerService.listBySupplierId(condition);
        return actionValueResult(pageCommonVO.getPageInfo());
    }

    @RequestMapping(value = "/invite", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true, code = AuthCode.Client.INVITE)
    public ActionResult<String> invite(@RequestBody CompanyDealerVO companyDealerVO) {
        if (companyDealerVO.getId() == null || companyDealerVO.getId() <= 0) {
            return actionResult(ErrorCode.IllegalArument);
        }
        ErrorCode code = companyDealerService.invite(companyDealerVO, getUserId(request));
        return actionResult(code, companyDealerVO.getInvitationCode());
    }

    /**
     * @return
     */
    @RequestMapping(value = "/bound", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true, code = AuthCode.Supplier.BIND)
    public ActionResult<String> boundSupplier(@RequestBody InvitationCodeVO invitationCodeVO) throws Exception {
        if (null == invitationCodeVO || StringUtil.isNullOrSpace(invitationCodeVO.getInvitationCode())) {
            return actionResult(ErrorCode.IllegalArument);
        }
        String orgId = getOrgId();
        return actionResult(companyDealerService.boundDealer(orgId, invitationCodeVO.getInvitationCode()));
    }

    @RequestMapping(value = "/isStorage", method = RequestMethod.GET)
    @FastMappingInfo(needLogin = true)
    public Integer isStorage(String orgId) throws Exception {
        return companyDealerService.isStorage(getOrgId(), orgId);
    }

    @RequestMapping(value = "/getDirectLimit", method = RequestMethod.GET)
    @FastMappingInfo(needLogin = true)
    public BigDecimal getDirectLimit(String orgId) throws Exception {
        return companyDealerService.getDirectLimit(getOrgId(), orgId);
    }

    @RequestMapping(value = "/getDirectLimitApply", method = RequestMethod.GET)
    @FastMappingInfo(needLogin = true)
    public BigDecimal getDirectLimitApply(String orgId) throws Exception {
        return companyDealerService.getDirectLimit(orgId, getOrgId());
    }

    @ResponseBody
    @RequestMapping(value = "/importDealerExcel", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult<Object> importDealerExcel(HttpServletRequest request) throws Exception {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile(multipartRequest.getFileNames().next());
        String fileName = file.getOriginalFilename();
        FunctionResult<Object> result = new FunctionResult<>();
        if (!fileName.trim().endsWith(".xls")) {
            result.setCode(ErrorCode.ImportExcelEndWithXLS);
        } else {
            result = companyDealerService.importDealerExcel(file, getOrgId());
        }
        return actionResult(result.getCode(), result.getValue());
    }

    @RequestMapping(value = "/downloadDealerExcel", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public void downloadDealerExcel() {
        companyDealerService.downloadDealerExcel();
    }

    @RequestMapping(value = "/saveClientReceiverInfo", method = RequestMethod.POST)
    @ApiOperation(value = "保存客户收货信息")
    @FastMappingInfo(needLogin = true)
    public ActionResult<String> saveClientReceiverInfo(@RequestBody ClientReceiverInfoVO clientReceiverInfoVO) {
        try {
            clientReceiverInfoVO.setOrgId(getOrgId());
            return actionResult(clientReceiverInfoService.save(clientReceiverInfoVO));
        } catch (Exception e) {
            return new ActionResult<>(ErrorCode.Failure.getCode(), e.getMessage());
        }
    }

    @RequestMapping(value = "/updateClientReceiverInfo", method = RequestMethod.POST)
    @ApiOperation(value = "修改客户收货信息")
    @FastMappingInfo(needLogin = true)
    public ActionResult<String> updateClientReceiverInfo(@RequestBody ClientReceiverInfoVO clientReceiverInfoVO) {
        try {
            return actionResult(clientReceiverInfoService.update(clientReceiverInfoVO));
        } catch (Exception e) {
            return new ActionResult<>(ErrorCode.Failure.getCode(), e.getMessage());
        }
    }

    @RequestMapping(value = "/getClientReceiverInfo", method = RequestMethod.GET)
    @ApiOperation(value = "修改客户收货信息")
    @FastMappingInfo(needLogin = true)
    public ActionResult<ClientReceiverInfoVO> getClientReceiverInfo(@RequestParam("id") String id) {
        if (StringUtils.isBlank(id)) {
           throw new CommonBusiExceptions(ErrorCode.IllegalArument.getDesc());
        }
        return actionValueResult(clientReceiverInfoService.getClientReceiverInfo(id));
    }

    @RequestMapping(value = "/deleteClientReceiverInfo", method = RequestMethod.POST)
    @ApiOperation(value = "删除客户收货信息")
    @FastMappingInfo(needLogin = true)
    public ActionResult<String> deleteClientReceiver(@RequestBody ClientReceiverInfoVO clientReceiverInfoVO) {
        ErrorCode result;
        try {
            result = clientReceiverInfoService.deleteById(clientReceiverInfoVO.getId());
        } catch (Exception e) {
            return actionResult(ErrorCode.Failure, e.getMessage());
        }
        return actionResult(result);
    }

    @RequestMapping(value = "/listClientReceiverInfo", method = RequestMethod.POST)
    @ApiOperation(value = "获取客户收货信息")
    @FastMappingInfo(needLogin = true)
    public ActionResult<Object> listClientReceivers(@RequestBody SearchCommonVO<ClientReceiverInfoVO> condition)
            throws Exception {
        condition.getFilters().setOrgId(getOrgId());
        PageCommonVO<Object> pageCommonVO = clientReceiverInfoService.list(condition);
        return actionValueResult(pageCommonVO.getPageInfo());
    }

    @RequestMapping(value = "/listSelfReceiversBySupplier", method = RequestMethod.POST)
    @ApiOperation(value = "获取在供应商客户信息中维护的自己的收货信息")
    @FastMappingInfo(needLogin = true)
    public ActionResult<Object> listSelfReceiversBySupplier(@RequestBody SupplierDealerSearchParam searchParam) throws Exception {
        return actionValueResult(clientReceiverInfoService.listSelfReceiversBySupplier(searchParam, getOrgId()));
    }

    @PostMapping(value = "/getRegularAgent")
    @FastMappingInfo(needLogin = true)
    @ApiOperation("获取常规代理商")
    public ActionResult<PageInfo<CompanyDealerVO>> getRegularAgent(@RequestBody SearchCommonVO<CompanyDealerVO> condition) throws Exception {
        CompanyDealerVO companyDealerVO = condition.getFilters();
        if (companyDealerVO == null) {
            companyDealerVO = new CompanyDealerVO();
        }
        companyDealerVO.setOrgId(getOrgId());
        condition.setFilters(companyDealerVO);
        PageCommonVO<CompanyDealerVO> pageCommonVO = companyDealerService.getRegularAgent(condition);
        return actionValueResult(pageCommonVO.getPageInfo());
    }

    @PostMapping(value = "/exportDealerVehicles")
    @FastMappingInfo(needLogin = true)
    @ApiOperation("导出客户车辆数据")
    public void exportDealerVehicles(CompanyDealerVO condition) throws Exception {
        if (null == condition) {
            condition = new CompanyDealerVO();
        }
        if (StringUtils.isBlank(condition.getOrgId())) {
            condition.setOrgId(getOrgId());
        }
        companyDealerService.exportDealerVehicles(condition);
    }


    @ApiOperation(value = "根据经纬度信息查询附近的代理商")
    @RequestMapping(value = "/queryDlsListByLatLong", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult<List<CompanyDealerVO>> queryDlsListByLatLong(@RequestBody CompanyDealerVO vo) {
        if (vo == null || StringUtils.isBlank(vo.getLatstr()) || StringUtils.isBlank(vo.getLongstr())) {
            return actionErrorResult("参数异常");
        }
        if (null == vo.getDistance()) {
            vo.setDistance(100d);
        }
        vo.setDealerType(2);
        vo.setOrgId(companyUtil.ynOrgId());
        try {
            Map<String, String> map = GeoUtil.returnLLSquarePoints(Double.valueOf(vo.getLongstr()), Double.valueOf(vo.getLatstr()), vo.getDistance());
            vo.setMaxLat(map.get("maxLat"));
            vo.setMinLat(map.get("minLat"));
            vo.setMaxLon(processLngFormat(map.get("maxLon")));
            vo.setMinLon(processLngFormat(map.get("minLon")));
        } catch (Exception e) {
            return actionErrorResult("经纬度信息转换失败" + e.getMessage());
        }
        List<CompanyDealerVO> list = companyDealerLatLngService.queryListByLatLong(vo);
        return actionValueResult(list);
    }


    @ApiOperation(value = "根据维修单经纬度查询附近的服务站")
    @RequestMapping(value = "/queryNearFwzListByLatLong", method = RequestMethod.POST)
    public ActionResult<List<CompanyDealerVO>> queryNearFwzListByLatLong(@RequestBody CompanyDealerParam vo) {
        if (vo == null || StringUtils.isBlank(vo.getSearchCenterCode()) || StringUtils.isBlank(vo.getLatstr()) || StringUtils.isBlank(vo.getLongstr())) {
            return actionErrorResult("参数异常");
        }
        if (null == vo.getLimit() || vo.getLimit() < 1) {
            vo.setLimit(5);
        }
        vo.setDealerType(5);
        List<CompanyDealerVO> list = companyDealerLatLngService.queryNearFwzListByLatLong(vo);
        return actionValueResult(list);
    }


    private String processLngFormat(String maxLon) {
        return maxLon + ",000000000";
    }

    public <T> ActionResult<T> actionErrorResult(String errmsg) {
        if (StringUtils.isBlank(errmsg)) {
            errmsg = ErrorCode.Failure.getDesc();
        }
        return new ActionResult<>(ErrorCode.Failure.getCode(),
                errmsg,
                null);
    }


    @ApiOperation(value = "初始化-将每个营销中心下的 代理商和服务站建立关联关系")
    @GetMapping(value = "/initDealer")
    @FastMappingInfo(needLogin = true)
    public ActionResult<String> initDealer() {
        String errMsg = companyDealerService.initDealer(companyUtil.ynOrgId());
        return actionValueResult(errMsg);
    }

    @ApiOperation(value = "绑定一个业务伙伴做供应商")
    @GetMapping(value = "/bindDealer")
    @FastMappingInfo(needLogin = true)
    public ActionResult<String> bindDealer(@RequestParam("platOrgId") String platOrgId) throws Exception {
        companyDealerService.bindDealerSupplierRelation(getOrgId(), platOrgId);
        return actionResult(ErrorCode.Success);
    }


    @ApiOperation(value = "为企业创建一个默认仓库库区储位")
    @GetMapping(value = "/addDefaultWarehouse")
    @FastMappingInfo(needLogin = true)
    public ActionResult<String> addDefaultWarehouse(@RequestParam("platOrgId") String platOrgId) {
        //新增默认仓库库区储位
        String msg = warehouseCompose.addDefaultWarehouseLocationWithoutE(platOrgId);
        if (StringUtils.isBlank(msg)) {
            return actionResult(ErrorCode.Success);
        } else {
            return actionValueResult(msg);
        }
    }
}
